package saver

import (
	"fmt"
	"github.com/jmoiron/sqlx"
	"my-crawler/concurrence/task/juchao/models"
	"my-crawler/database/mysql"
)

func Saver() chan interface{} {
	out := make(chan interface{}, 1)
	client := mysql.Db
	go func() {
		itemCount := 0
		for {
			item := <-out //接收 engine发过来的item
			fmt.Println(item)
			itemCount++
			UpdateInMysql(client, item)
		}
	}()
	return out
}

func UpdateInMysql(db *sqlx.DB, item interface{}) {
	i := item.(models.Result)
	if len(i.Data.Records) < 1 {
		return
	}
	r := i.Data.Records[0]
	bf := r.BasicInformation[0]
	lf := r.ListingInformation[0]

	res, err := db.Exec("update  2022_juchao  set F004V=? ,F006D = ?,F010D = ?,MARKET = ?,ORGNAME = ?,F007N = ?,F008N = ?,F047V = ? where id=?",
		bf.F004V, bf.F006D, bf.F010D, bf.MARKET, bf.ORGNAME, lf.F007N, lf.F008N, lf.F047V, i.ID)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return
	}
	row, err := res.RowsAffected()
	if err != nil {
		fmt.Println("rows failed, ", err)
	}
	fmt.Println("update succ:", row)
}
